package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.dialog.SceneTaskSortDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshLinkageEvent;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.ui.adapter.LinkageConditionAdapter;
import com.qiantu.phone.ui.adapter.LinkageTaskAdapter;
import com.qiantu.phone.ui.dialog.BottomDelayTimeDialog;
import com.qiantu.phone.ui.dialog.BottomDeviceDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.SelectDecideTypeDialog;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class EditLinkageActivity extends AppActivity {
    private SettingBar setName;
    private SettingBar setRoom;
    private TextView btnConditionType;
    private ImageView addCondition;
    private ImageView addTask;
    private LinkageBean mLinkageBean;
    private List<LinkageBean.LinkageCondition> mLinkageConditions;
    private List<LinkageBean.LinkageTask> mLinkageTasks;
    private RecyclerView vConditionList;
    private RecyclerView vTaskList;
    private View vDeleteLinkage;
    private boolean isCreate;
    //    private BottomDelayTimeDialog mBottomDelayTimeDialog;
    private SelectDecideTypeDialog mSelectDecideTypeDialog;
    private int deleteTaskPosition;
    private int deleteConditionPosition;
    //联动条件满足类型  默认全部满足
    private int mDecideType = 1;
    private LinkageTaskAdapter mLinkageTaskAdapter;
    private LinkageConditionAdapter mLinkageConditionAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_linkage;
    }

    @Override
    protected void initView() {
        setName = findViewById(R.id.set_name);
        setRoom = findViewById(R.id.set_room);
        btnConditionType = findViewById(R.id.btn_condition_type);
        addCondition = findViewById(R.id.add_condition);
        addTask = findViewById(R.id.add_task);
        vConditionList = findViewById(R.id.condition_list);
        vTaskList = findViewById(R.id.task_list);
        vDeleteLinkage = findViewById(R.id.delete_linkage);
        setOnClickListener(setName, setRoom, btnConditionType, addCondition, addTask, vDeleteLinkage);
        getTitleBar().getRightView().setSelected(false);
    }

    @Override
    protected void initData() {
        mLinkageBean = LinkageDataHolder.getLinkageData();
        if (mLinkageBean == null) {
            LinkageBean addLinkage = new LinkageBean();
            LinkageDataHolder.setLinkageData(addLinkage);
            mLinkageBean = addLinkage;
        }
        //默认设置条件
        if(mLinkageBean.getDecideType() == 0){
            mLinkageBean.setDecideType(mDecideType);
        }
        setName.setRightText(mLinkageBean.getName());
        String floorRoomName = LLRoomDBManager.getInstance(getContext()).getFloorRoomName(mLinkageBean.getRoomSerialNo());
        setRoom.setRightText(floorRoomName);
        mDecideType = mLinkageBean.getDecideType();
        switch (mDecideType) {
            case 1:
                btnConditionType.setText(R.string.all_conditions_must_be_met);
                break;
            case 2:
                btnConditionType.setText(R.string.only_one_of_conditions_needs_to_be_met);
                break;
        }
        mLinkageBean.setHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        if (mLinkageBean.getLinkageConditions() == null) {
            mLinkageBean.setLinkageConditions(new ArrayList<>());
        }
        if (mLinkageBean.getLinkageTasks() == null) {
            mLinkageBean.setLinkageTasks(new ArrayList<>());
        }
        mLinkageConditions = mLinkageBean.getLinkageConditions();
        mLinkageConditionAdapter = new LinkageConditionAdapter();
        mLinkageConditionAdapter.targetSerialNo = getString("targetSerialNo");
        mLinkageConditionAdapter.setData(mLinkageConditions);
        vConditionList.setLayoutManager(new LinearLayoutManager(getContext()));
        vConditionList.setAdapter(mLinkageConditionAdapter);
        mLinkageConditionAdapter.setClickListener(new LinkageConditionAdapter.ClickListener() {
            @Override
            public void onDelete(int position) {
                deleteConditionPosition = position;
                showDeleteConditionHintDialog();
            }

            @Override
            public void onEdit(int position) {
                Log.i("debug", "position: " + position);
                Log.i("debug", "mLinkageConditions size: " + mLinkageConditions.size());
                Log.i("debug", "adapter data size: " + mLinkageConditionAdapter.getData().size());
                Log.i("debug", "adapter data content: " + mLinkageConditionAdapter.getData().toString());
                if (position >= 0 && position < mLinkageConditionAdapter.getData().size()) {
                    LinkageBean.LinkageCondition linkageCondition = mLinkageConditionAdapter.getData().get(position);
                    Log.i("debug", "selected condition: " + linkageCondition.toString());
                    gotoEditCondition(linkageCondition);
                } else {
                    Log.e("debug", "Invalid position: " + position);
                }
            }
        });

        List<LinkageBean.LinkageTask> newTasks = new ArrayList<>();
        int time = 0;
        for(int i = 0;i < mLinkageBean.getLinkageTasks().size();i++){
            LinkageBean.LinkageTask bean = mLinkageBean.getLinkageTasks().get(i);
            if(bean.getTaskType() == 1){
                Map<String,String> map = bean.getDeviceStateData().getStatus();
                if(map.get("red") != null){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("red",map.get("red"));
                    jsonObject.put("green",map.get("green"));
                    jsonObject.put("blue",map.get("blue"));
                    map.remove("red");
                    map.remove("green");
                    map.remove("blue");
                    map.put("colorValue",jsonObject.toString());
                }
                if(map.get("songid") != null) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("songname",map.get("songname"));
                    jsonObject.put("songpicurl",map.get("songpicurl"));
                    jsonObject.put("musicid",map.get("songid"));
                    map.remove("songname");
                    map.remove("songid");
                    map.remove("songpicurl");
                    map.put("songinfo",jsonObject.toString());
                }
            }
            bean.setTriggerTime(time + bean.getTriggerTime());
            if(bean.getTaskType() == 2){
                time += bean.getLongTime();
            }else{
                newTasks.add(bean);
            }
        }
        mLinkageBean.setLinkageTasks(newTasks);
        mLinkageTasks = mLinkageBean.getLinkageTasks();
        mLinkageTaskAdapter = new LinkageTaskAdapter();
        mLinkageTaskAdapter.targetSerialNo = getString("targetSerialNo");
        mLinkageTaskAdapter.setData(mLinkageTasks);
        vTaskList.setLayoutManager(new LinearLayoutManager(getContext()));
        vTaskList.setAdapter(mLinkageTaskAdapter);
        mLinkageTaskAdapter.setClickListener(new LinkageTaskAdapter.ClickListener() {
            @Override
            public void onDelete(int position) {
                deleteTaskPosition = position;
                showDeleteTaskHintDialog();
            }

            @Override
            public void onEdit(int position) {
                editTask(position);
            }

            @Override
            public void onSort(int position){
                showBottomSceneTaskSortDialog(position);
            }

            @Override
            public void onDelay(int position){
                showBottomTimeDialog(position);
            }
        });

        if (TextUtils.isEmpty(mLinkageBean.getLinkageSerialNo())) {
            setTitle(getString(R.string.create_linkage));
            isCreate = true;
            vDeleteLinkage.setVisibility(View.GONE);
        } else {
            setTitle(getString(R.string.edit_linkage));
            isCreate = false;
            vDeleteLinkage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mLinkageBean = LinkageDataHolder.getLinkageData();
        mLinkageConditions = mLinkageBean.getLinkageConditions();
        mLinkageTasks = mLinkageBean.getLinkageTasks();
        mLinkageConditionAdapter.notifyDatasetChanged();
        mLinkageTaskAdapter.notifyDataSetChanged();
        checkRightClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void gotoEditCondition(LinkageBean.LinkageCondition linkageCondition){
        Log.i("boyun", "gotoEditCondition: " + linkageCondition);
        Intent intent = null;
        /**
         * 定时 : 1 ,
         * 环境温度 : 2 ,
         * 环境湿度 : 3 ,
         * 环境天气 : 4 ,
         * 环境空气质量 : 5 ,
         * 环境日出日落 : 6 ,
         * 定位 : 7 ,
         * 设备状态 : 8 ,
         * 人体感应 : 9 ,
         * 人体存在感应 : 10 ,
         * 场景触发 : 11
         */
        switch (linkageCondition.getConditionType()){
            case 1:
                intent = new Intent(this, EditTimeActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 2:
                intent = new Intent(this, TemperatureActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 3:
                intent = new Intent(this, HumidityActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 4:
                intent = new Intent(this, WeatherActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 5:
                intent = new Intent(this, AirQualityActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 6:
                intent = new Intent(this, SunriseSunsetActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 7:
//                intent = new Intent(this, LocationActivity.class);
//                intent.putExtra("serial_no", linkageCondition.getSerialNo());
//                intent.putExtra("type", 2);
//                startActivity(intent);
                LocationActivity.start(this, linkageCondition.getConditionSerialNo(), 2);
                break;
            case 8:
//                intent = new Intent(this, SelectDeviceStatusActivity.class);
//                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
//                intent.putExtra("device_serial_no", linkageCondition.getDeviceSerialNo());
//                startActivity(intent);
                DeviceBean device = LLDeviceDBManager.getInstance(getContext()).get(linkageCondition.getDeviceSerialNo());
                LLDeviceUtil.startDeviceStatusActivity(getContext(), linkageCondition.getStateName(), device, linkageCondition.getConditionSerialNo());
                break;
            case 9:
                intent = new Intent(this, HumanBodyInductionActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 10:
            case 16:
            case 17:
            case 18:
            case 19:
            case 20:
            case 21:
            case 22:
            case 23:
            case 24:
                intent = new Intent(this, HumanPresenceInductionActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
                break;
            case 12:
            case 13:
            case 14:
                intent = new Intent(this, NoiseActivity.class);
                intent.putExtra("serial_no", linkageCondition.getConditionSerialNo());
                startActivity(intent);
        }
    }

    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        String tip = isCreate ? getString(R.string.create_back_hint) : getString(R.string.edit_back_hint);
        if (!isCreate) {//修改场景
            if (getTitleBar().getRightView().isSelected()) {//已经有数据修改
                new ConfirmHintDialog.Builder(this)
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.back))
                        .setContent(tip)
                        .setLeftBtnStrongHint(true)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                finish();
                            }
                        })
                        .show();
            } else {
                finish();
            }
        } else {
            //已经有数据填写
            if (mLinkageBean == null || !TextUtils.isEmpty(mLinkageBean.getName())
                    || mLinkageBean.getLinkageConditions().size() > 0 || mLinkageBean.getLinkageTasks().size() > 0) {
                new ConfirmHintDialog.Builder(this)
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.back))
                        .setContent(tip)
                        .setLeftBtnStrongHint(true)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                finish();
                            }
                        })
                        .show();
            } else {
                finish();
            }
        }
    }

    @Override
    public void finish() {
        LinkageDataHolder.clearLinkageData();
        super.finish();
    }

    @Override
    public void onRightClick(View view) {
        if(TextUtils.isEmpty(mLinkageBean.getName())){
            toast(R.string.please_set_name);
            return;
        }
        List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
        if(linkageConditions == null || linkageConditions.size() == 0){
            toast(R.string.please_add_linkage_condition);
            return;
        }
        List<LinkageBean.LinkageTask> linkageTasks = mLinkageBean.getLinkageTasks();
        if(linkageTasks == null || linkageTasks.size() == 0){
            toast(R.string.please_add_valid_task);
            return;
        }
        boolean isAllDelayTask = true;
        for(LinkageBean.LinkageTask task : linkageTasks){
            if(task.getTaskType() != 2){
                isAllDelayTask = false;
            }
            if(task.getTaskType() == 1){
                LinkageBean.LinkageTask.DeviceStateDataDTO stateData = task.getDeviceStateData();
                if(stateData.getStatus().get("colorValue") != null){
                    Map<String, String> map = stateData.getStatus();
                    JSONObject jsonObject =  JSONObject.parseObject(map.get("colorValue"));
                    stateData.getStatus().put("red",jsonObject.getString("red"));
                    stateData.getStatus().put("green",jsonObject.getString("green"));
                    stateData.getStatus().put("blue",jsonObject.getString("blue"));
                    stateData.getStatus().remove("colorValue");
                }
                if(stateData.getStatus().get("songinfo") != null) {
                    Map<String, String> map = stateData.getStatus();
                    JSONObject jsonObject =  JSONObject.parseObject(map.get("songinfo"));
                    stateData.getStatus().put("songname",jsonObject.getString("songname"));
                    stateData.getStatus().put("songpicurl",jsonObject.getString("songpicurl"));
                    stateData.getStatus().put("songid",jsonObject.getString("musicid"));
                    stateData.getStatus().remove("songinfo");
                }
            }
        }
        if(isAllDelayTask){
            toast(R.string.please_add_valid_task);
            return;
        }
        mLinkageBean.setIsDisable(false);
        if (isCreate) {
            LLHttpManager.linkageCreate(this, mLinkageBean, new HttpCallback<HttpData<LinkageBean>>(this) {
                @Override
                public void onSucceed(HttpData<LinkageBean> result) {
                    super.onSucceed(result);
                    LinkageDataHolder.clearLinkageData();
                    EventBus.getDefault().post(new RefreshLinkageEvent());
                    finish();
//                    startActivity(HomeActivity.class);
                }
            });
        } else {
            RoomBean roomBean = LLRoomDBManager.getInstance(this).getRoomByRoomSerialNo(mLinkageBean.getRoomSerialNo());
            if (roomBean == null){
                toast(R.string.linkage_no_room);
                return;
            }

            LLHttpManager.linkageEdit(this, mLinkageBean, new HttpCallback<HttpData<LinkageBean>>(this) {
                @Override
                public void onSucceed(HttpData<LinkageBean> result) {
                    super.onSucceed(result);
                    LinkageDataHolder.clearLinkageData();
                    EventBus.getDefault().post(new RefreshLinkageEvent());
                    finish();
//                    startActivity(HomeActivity.class);
                }
            });
        }
    }

    private void checkRightClick() {
        getTitleBar().getRightView().setSelected(isDataComplete());
    }

    private boolean isDataComplete() {
        if (mLinkageBean == null) return false;
        if (TextUtils.isEmpty(mLinkageBean.getName())) return false;
        if (mLinkageBean.getLinkageConditions() == null || mLinkageBean.getLinkageConditions().size() == 0 || mLinkageBean.getLinkageTasks() == null || mLinkageBean.getLinkageTasks().size() == 0)
            return false;
        return true;
    }

    private void showSelectDecideTypeDialog() {
        if (mSelectDecideTypeDialog == null) {
            mSelectDecideTypeDialog = new SelectDecideTypeDialog(getContext());
            mSelectDecideTypeDialog.setDialogClickListener(new SelectDecideTypeDialog.DialogClickListener() {
                @Override
                public void onSelected(int decideType) {
                    mDecideType = decideType;
                    switch (mDecideType) {
                        case 1:
                            btnConditionType.setText(R.string.all_conditions_must_be_met);
                            break;
                        case 2:
                            btnConditionType.setText(R.string.only_one_of_conditions_needs_to_be_met);
                            break;
                    }
                    mLinkageBean.setDecideType(mDecideType);
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(btnConditionType)
                    .asCustom(mSelectDecideTypeDialog);
        }
        mSelectDecideTypeDialog.show();
    }

    @Override
    public void onClick(View view) {
        if (view == setName) {
            showBottomEditDialog(setName.getRightText().toString().trim());
        }else if(view == setRoom){
            gotoFloorRoomView();
        } else if (view == btnConditionType) {
            showSelectDecideTypeDialog();
        } else if (view == addCondition) {
            Intent intent = new Intent(this, AddConditionActivity.class);
            intent.putExtra("type", AddConditionActivity.TYPE_LINKAGE);
            startActivity(intent);
        } else if (view == addTask) {
            Intent intent = new Intent(this, AddTaskActivity.class);
            intent.putExtra("type", AddTaskActivity.TYPE_LINKAGE);
            startActivity(intent);
        } else if (view == vDeleteLinkage) {
            showConfirmCancelHintDialog(getString(R.string.delete_linkage_hint), getString(R.string.cancel), getString(R.string.delete_text), new ConfirmCancelHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onRightClick(BaseDialog dialog) {
                    dialog.dismiss();
                    LLHttpManager.deleteLinkage((LifecycleOwner) getActivity(), mLinkageBean.getLinkageSerialNo(), new HttpCallback<HttpData<Void>>(null) {
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            super.onSucceed(result);
                            LinkageDataHolder.clearLinkageData();
                            finish();
                        }
                    });
                }
            });

        }
    }

    BottomEditDialog mBottomEditDialog;

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setLabel(getString(R.string.linkage_name));
            mBottomEditDialog.setHint(getString(R.string.please_enter_linkage_name));
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    setName.setRightText(mBottomEditDialog.getText());
                    mLinkageBean.setName(mBottomEditDialog.getText());
                    checkRightClick();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.LINKAGE_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void gotoFloorRoomView(){
        Intent intent = new Intent(this, SelectFloorRoomActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("roomSerialNo", mLinkageBean.getRoomSerialNo());
        intent.putExtra("linkType", mLinkageBean.getLinkType());
        intent.putExtra("title", this.getString(R.string.affiliation_room));
        intent.putExtra("selectType",2);
        startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (resultCode == Activity.RESULT_OK) {
                    String selectRoomSerialNo = data.getStringExtra("serialNo");
                    if (RoomBean.ROOM_COMMON_SERIALNO.equals(selectRoomSerialNo)) {
                        mLinkageBean.setLinkType(2);
                    } else {
                        mLinkageBean.setLinkType(1);
                    }
                    mLinkageBean.setRoomSerialNo(selectRoomSerialNo);
                    String floorRoomName = LLRoomDBManager.getInstance(getContext()).getFloorRoomName(selectRoomSerialNo);
                    setRoom.setRightText(floorRoomName);
                    checkRightClick();
                }
            }
        });
    }

    private void showDeleteConditionHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                mLinkageConditions.remove(deleteConditionPosition);
                //notifyItemRemoved(position);
                mLinkageConditionAdapter.notifyDataSetChanged();
                mLinkageConditionAdapter.mItemManger.closeAllItems();
                checkRightClick();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_condition_hint));
        mConfirmCancelHintDialog.show();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;

    private void showDeleteTaskHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                mLinkageTasks.remove(deleteTaskPosition);
                //notifyItemRemoved(position);
                mLinkageTaskAdapter.notifyDataSetChanged();
                mLinkageTaskAdapter.mItemManger.closeAllItems();
                checkRightClick();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_task_hint));
        mConfirmCancelHintDialog.show();
    }

    private SceneTaskSortDialog mSceneTaskSortDialog;
    private void showBottomSceneTaskSortDialog(int position){
        if (mSceneTaskSortDialog == null) {
            mSceneTaskSortDialog = new SceneTaskSortDialog(getActivity());
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mSceneTaskSortDialog);
        }
        mSceneTaskSortDialog.setDialogClickListener(new SceneTaskSortDialog.DialogClickListener() {
            @Override
            public void onConfirmClick(int index) {
                mSceneTaskSortDialog.dismiss();
                LinkageBean.LinkageTask taskBean = mLinkageTasks.get(position);
                mLinkageTasks.remove(position);
                mLinkageTasks.add(index,taskBean);
                //notifyItemRemoved(position);
                mLinkageTaskAdapter.notifyDataSetChanged();
                mLinkageTaskAdapter.closeAllItems();
                checkRightClick();
            }
        });


        int time = mLinkageTasks.get(position).getTriggerTime();
        int beginIndex = 0,endIndex = 0;
        boolean isBegin = false;
        boolean isEnd = false;
        for(int i = 0;i < mLinkageTasks.size();i++){
            LinkageBean.LinkageTask bean = mLinkageTasks.get(i);
            int sortTime = bean.getTriggerTime();
            if(sortTime == time && !isBegin){
                isBegin = true;
                beginIndex = i;
            }
            if(isBegin && sortTime != time){
                endIndex = i - 1;
                isEnd = true;
                break;
            }
        }
        if(isBegin && !isEnd){
            endIndex = mLinkageTasks.size() - 1;
        }
        mSceneTaskSortDialog.setData(position,beginIndex + 1,endIndex + 1);
        mSceneTaskSortDialog.setLabel("滑动设定该设备在此场景/联动中的序号");
        mSceneTaskSortDialog.show();
    }

    private BottomDelayTimeDialog mBottomDelayTimeDialog;
    public void showBottomTimeDialog(int position){
        if (mBottomDelayTimeDialog == null) {
            mBottomDelayTimeDialog = new BottomDelayTimeDialog(this);

            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomDelayTimeDialog);
        }
        LinkageBean.LinkageTask taskBean = mLinkageTasks.get(position);
        mBottomDelayTimeDialog.setDialogClickListener(new BottomDelayTimeDialog.DialogClickListener() {
            @Override
            public void onConfirmClick(String time, int longTime) {
                mBottomDelayTimeDialog.dismiss();
                updateTime(position,longTime);
            }
        });
        mBottomDelayTimeDialog.setMillisecond(taskBean.getTriggerTime());
        mBottomDelayTimeDialog.show();
    }

    private void updateTime(int position,int longTime){
        mLinkageTasks.get(position).setTriggerTime(longTime);
        mLinkageTasks.sort(new Comparator<LinkageBean.LinkageTask>(){
            @Override
            public int compare(LinkageBean.LinkageTask o1, LinkageBean.LinkageTask o2) {
                int time1 = o1.getTriggerTime();
                int time2 = o2.getTriggerTime();
                if(time1 == time2){
                    return o1.getSort() - o2.getSort();
                }
                return time1 - time2;
            }
        });
        mLinkageTaskAdapter.notifyDataSetChanged();
    }

    private void editTask(int position) {
        LinkageBean.LinkageTask linkageTask = mLinkageTasks.get(position);
        //1设备指令、2延时、3发送消息、4联动启停、5一键场景
        switch (linkageTask.getTaskType()) {
            case 1: {//1设备指令
                showDeviceDialog(linkageTask, position);
                break;
            }
            case 2: {//2延时
//                showBottomTimeDialog(linkageTask, position);
                break;
            }
            case 3: {//3发送消息
                Intent intent = new Intent(this, PushMessageSettingActivity.class);
                intent.putExtra("serial_no", linkageTask.getTaskSerialNo());
                intent.putExtra("type", AddTaskActivity.TYPE_LINKAGE);
                startActivity(intent);
                break;
            }
            case 4: {//4联动启停
                Intent intent = new Intent(this, LinkageStartStopActivity.class);
                intent.putExtra("serial_no", linkageTask.getTaskSerialNo());
                intent.putExtra("type", AddTaskActivity.TYPE_LINKAGE);
                startActivity(intent);
                break;
            }
            case 5: {//5一键场景
                Intent intent = new Intent(this, OnKeySceneSelectActivity.class);
                intent.putExtra("serial_no", linkageTask.getTaskSerialNo());
                startActivity(intent);
                break;
            }
            case 9: {//5一键场景
                showGroupDialog(linkageTask, position);
                break;
            }

        }
    }

    private BottomDeviceDialog mDeviceDialog;

    private void showDeviceDialog(LinkageBean.LinkageTask linkageTask, int position) {
        LinkageBean.LinkageTask.DeviceStateDataDTO deviceItemStateData = linkageTask.getDeviceStateData();
        DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).get(linkageTask.getDeviceSerialNo());
        mDeviceDialog = new BottomDeviceDialog(this) {
            @Override
            public void onSave(Map<String, String> statusJson,List<DeviceBean> deviceBeans) {
                deviceItemStateData.setStatus(statusJson);
                mLinkageTaskAdapter.notifyItemChanged(position);
                checkRightClick();
            }
        };
        new XPopup.Builder(this)
                .dismissOnBackPressed(true)
                .enableDrag(false)
                .asCustom(mDeviceDialog);
        mDeviceDialog.setDeviceBean(deviceBean, deviceItemStateData.getStatus());
        mDeviceDialog.show();
    }

    private void showGroupDialog(LinkageBean.LinkageTask linkageTask, int position) {
        LinkageBean.LinkageTask.DeviceStateDataDTO deviceItemStateData = linkageTask.getStateData();
        DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).get(linkageTask.getDeviceGroupSerialNo());
        mDeviceDialog = new BottomDeviceDialog(this) {
            @Override
            public void onSave(Map<String, String> statusJson,List<DeviceBean> deviceBeans) {
                deviceItemStateData.setStatus(statusJson);
                mLinkageTaskAdapter.notifyItemChanged(position);
                checkRightClick();
            }
        };
        new XPopup.Builder(this)
                .dismissOnBackPressed(true)
                .enableDrag(false)
                .asCustom(mDeviceDialog);
        mDeviceDialog.setDeviceBean(deviceBean, deviceItemStateData.getStatus());
        mDeviceDialog.show();
    }

//    private void showBottomTimeDialog(LinkageBean.LinkageTask linkageTask, int position) {
//        if (mBottomDelayTimeDialog == null) {
//            mBottomDelayTimeDialog = new BottomDelayTimeDialog(this);
//            mBottomDelayTimeDialog.setDialogClickListener(new BottomDelayTimeDialog.DialogClickListener() {
//                @Override
//                public void onConfirmClick(String time, int longTime) {
//                    mBottomDelayTimeDialog.dismiss();
//                    linkageTask.setLongTime(longTime);
//                    mLinkageTaskAdapter.notifyItemChanged(position);
//                    checkRightClick();
//                }
//            });
//            new XPopup.Builder(this)
//                    .dismissOnBackPressed(true)
//                    .enableDrag(true)
//                    .asCustom(mBottomDelayTimeDialog);
//        }
//        mBottomDelayTimeDialog.setMillisecond(linkageTask.getLongTime());
//        mBottomDelayTimeDialog.show();
//    }
}